package com.beta.backend.gateway.filter;

import com.beta.backend.gateway.config.GatewayCfgBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 获取公共参数
 * 1、业务端类型（endType）：C端（C）、B端（B）
 * 2、渠道类型（channel）：企微（QIWEI）、微信（WEIXIN）、手机银行APP、浏览器网站
 * 3、终端类型（clientType）：手机（MOBILE）、PC（PC）、平板（MOBILE）
 */
@Slf4j
@Component
public class GatewayBaseFilter extends AbstractGatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    private GatewayCfgBean gatewayCfgBean;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest().mutate().build();
        HttpHeaders headers = request.getHeaders();

        String endType = headers.getFirst(END_TYPE_HEADER);
        if (StringUtils.isEmpty(endType)) {
            endType = request.getQueryParams().getFirst(END_TYPE_HEADER);
        }

        String channel = headers.getFirst(CHANNEL_HEADER);
        if (StringUtils.isEmpty(channel)) {
            channel = request.getQueryParams().getFirst(CHANNEL_HEADER);
        }

        String clientType = headers.getFirst(CLIENT_TYPE_HEADER);
        if (StringUtils.isEmpty(clientType)) {
            clientType = request.getQueryParams().getFirst(CLIENT_TYPE_HEADER);
        }

        if (StringUtils.isEmpty(endType)) {
            // 默认企微端为B端，微信端为C端
            if (StringUtils.equals(channel, QIWEI_CHANNEL_VALUE)) {
                endType = "B";
            } else if (StringUtils.equals(channel, WEIXIN_CHANNEL_VALUE)) {
                endType = "C";
            }
        }

        if (gatewayCfgBean.isLogRequest()) {
            log.info("客户端特征: endType = {}, channel = {}, clientType = {}", endType, channel, clientType);
        }

        return chain.filter(exchange.mutate().request(request.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return 1;
    }

}
